package com.gs.auth.service.impl;

import com.gs.auth.po.TbUser;
import com.gs.auth.service.LoginService;
import com.gs.auth.service.UserService;
import com.gs.auth.vo.LoginVo;
import com.gs.common.constant.Constants;
import com.gs.common.core.redis.RedisCache;
import com.gs.common.enums.ExceptionCode;
import com.gs.common.exception.CustomException;
import com.gs.common.utils.StringUtils;
import com.gs.common.utils.sign.Md5Utils;
import com.gs.common.utils.token.JwtTokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private RedisCache redisCache;
    @Resource
    private UserService userService;
    @Override
    public String login(LoginVo loginVo) {
        String redisCode = redisCache.getCacheObject(
                Constants.CAPTCHA_CODE_KEY +
                        loginVo.getUuid());
        if(!StringUtils.equals(redisCode,loginVo.getCode())){
            throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }
        String pwd= Md5Utils.hash(Md5Utils.hash(loginVo.getPassword()));
        TbUser login = userService.selectUser(loginVo.getUsername(),pwd);
        if(Objects.isNull(login)){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }
        String token=JwtTokenUtils.generateJwtToken(login.getUserId(),loginVo.getUsername(),login.getUserAccount());

        return token;

    }

    @Override
    public String webLogin(LoginVo loginVo) {
        String redisCode = redisCache.getCacheObject(
                Constants.CAPTCHA_CODE_KEY +
                        loginVo.getUuid());
        if(!StringUtils.equals(redisCode,loginVo.getCode())){
            throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }
        String pwd= Md5Utils.hash(Md5Utils.hash(loginVo.getPassword()));
        TbUser login = userService.selectUser(loginVo.getUsername(),pwd);
        if(Objects.isNull(login)){
            throw new CustomException(ExceptionCode.INVALID_USERNAME_PASSWORD);
        }
        String token=JwtTokenUtils.generateWebJwtToken(login.getUserId(),loginVo.getUsername(),login.getUserAccount());
        redisCache.setCacheObject(token,token,3, TimeUnit.MINUTES);
        return token;
    }
}
